package com.papercutting.platform.controller.admin;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.query.UserQuery;
import com.papercutting.platform.dto.request.UserCreateRequest;
import com.papercutting.platform.dto.request.UserUpdateRequest;
import com.papercutting.platform.dto.response.PageResult;
import com.papercutting.platform.dto.response.UserResponse;
import com.papercutting.platform.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 */
@Slf4j
@RestController("adminUserController")
@RequestMapping("/api/admin/users")
@RequiredArgsConstructor
@Validated
public class UserController {
    
    private final UserService userService;
    
    /**
     * 创建用户
     */
    @PostMapping
    public Result<Long> createUser(@Valid @RequestBody UserCreateRequest request) {
        log.info("创建用户请求: {}", request.getNickname());
        
        Long userId = userService.createUser(request);
        
        return Result.success("用户创建成功", userId);
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{id}")
    public Result<Void> updateUser(
            @PathVariable @NotNull Long id,
            @Valid @RequestBody UserUpdateRequest request) {
        log.info("更新用户请求: {}", id);
        
        request.setId(id);
        userService.updateUser(request);
        
        return Result.success("用户更新成功");
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable @NotNull Long id) {
        log.info("删除用户请求: {}", id);
        
        userService.deleteUser(id);
        
        return Result.success("用户删除成功");
    }
    
    /**
     * 批量删除用户
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteUsers(@RequestBody @NotEmpty List<Long> userIds) {
        log.info("批量删除用户请求: {}", userIds);
        
        userService.batchDeleteUsers(userIds);
        
        return Result.success("用户批量删除成功");
    }
    
    /**
     * 根据ID获取用户信息
     */
    @GetMapping("/{id}")
    public Result<UserResponse> getUserById(@PathVariable @NotNull Long id) {
        UserResponse user = userService.getUserById(id);
        
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        return Result.success(user);
    }
    
    /**
     * 分页查询用户列表
     */
    @GetMapping
    public Result<PageResult<UserResponse>> getUserPage(UserQuery query) {
        log.info("分页查询用户列表: {}", query);
        
        PageResult<UserResponse> pageResult = userService.getUserPage(query);
        
        return Result.success(pageResult);
    }
    
    /**
     * 获取用户列表（不分页）
     */
    @GetMapping("/list")
    public Result<List<UserResponse>> getUserList(UserQuery query) {
        log.info("查询用户列表: {}", query);
        
        List<UserResponse> users = userService.getUserList(query);
        
        return Result.success(users);
    }
    
    /**
     * 更新用户状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateUserStatus(
            @PathVariable @NotNull Long id,
            @RequestParam @NotNull Integer status) {
        log.info("更新用户状态请求: {} -> {}", id, status);
        
        userService.updateUserStatus(id, status);
        
        return Result.success("用户状态更新成功");
    }
    
    /**
     * 批量更新用户状态
     */
    @PutMapping("/batch/status")
    public Result<Void> batchUpdateUserStatus(
            @RequestBody @NotEmpty List<Long> userIds,
            @RequestParam @NotNull Integer status) {
        log.info("批量更新用户状态请求: {} -> {}", userIds, status);
        
        userService.batchUpdateUserStatus(userIds, status);
        
        return Result.success("用户状态批量更新成功");
    }
    
    /**
     * 重置用户密码
     */
    @PutMapping("/{id}/password/reset")
    public Result<Void> resetUserPassword(
            @PathVariable @NotNull Long id,
            @RequestBody Map<String, String> request) {
        log.info("重置用户密码请求: {}", id);

        String newPassword = request.get("newPassword");
        if (newPassword == null || newPassword.trim().isEmpty()) {
            return Result.error("新密码不能为空");
        }

        if (newPassword.length() < 6) {
            return Result.error("密码长度至少6位");
        }

        userService.resetPassword(id, newPassword);

        return Result.success("密码重置成功");
    }
    
    /**
     * 检查用户名是否存在
     */
    @GetMapping("/check/nickname")
    public Result<Boolean> checkNickname(@RequestParam @NotNull String nickname) {
        boolean exists = userService.existsByNickname(nickname);
        return Result.success(exists);
    }
    
    /**
     * 检查手机号是否存在
     */
    @GetMapping("/check/phone")
    public Result<Boolean> checkPhone(@RequestParam @NotNull String phone) {
        boolean exists = userService.existsByPhone(phone);
        return Result.success(exists);
    }
    
    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/check/email")
    public Result<Boolean> checkEmail(@RequestParam @NotNull String email) {
        boolean exists = userService.existsByEmail(email);
        return Result.success(exists);
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getUserStats() {
        Map<String, Object> stats = userService.getUserStats();
        return Result.success(stats);
    }
}